#include "forkos/types.h"

static uint32_t screen_width; 
static uint32_t screen_height;
static uint32_t bytes_per_line;

static uint32_t current_line = 0;
static uint32_t current_char = 0;

static uint32_t ega_error_code = 1;

static uint16_t *ega_framebuffer = (uint16_t*)0x000b8000;

void ega_init() {
    screen_width = 80;
    screen_height = 25;
    bytes_per_line = screen_width * 2;
    ega_error_code = 0;
}

uint32_t ega_get_error() {
    return ega_error_code; 
}

void ega_print_string(char *str, uint8_t color) {
    for (; *str; str++) {
        char ch = *str;
        if (ch == '\n') {
            current_char = 0;
            if (++current_line >= screen_height) {
                current_line = 0;
            }
        } else {
            ega_framebuffer[current_char + current_line*bytes_per_line] = (uint16_t)((color << 8) | ch);

            if (++current_char >= screen_width) {
                current_char = 0;
                if (++current_line >= screen_height) {
                    current_line = 0;
                }
            }
        }
    }
}

// TODO: extend to support more radices
void ega_print_int(uint32_t n, uint8_t color) {
    char buf[32];

    uint32_t rem;
    uint32_t i = 0;
    uint32_t start = 0;
    // TODO: Prevent buffer overflow
    while (n > 0) {
        rem = n % 10;
        buf[i] = (char)(0x30 + rem); 
        i++;
        n /= 10;
    }
    buf[i] = '\0';
    i--; 

    // reverse
    while (i > start) {
        // don't like this declaration inside a loop,
        // alas i am too lazy
        char tmp = buf[start];
        buf[start] = buf[i];
        buf[i] = tmp;
        i--;
        start++;
    }
    
    ega_print_string(buf, color);
}